package com.zebra.remoting.protocol;

import cn.hutool.core.util.StrUtil;
import com.zebra.common.ZebraBaseMessage;
import com.zebra.remoting.config.BasisCommandCode;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Date 2020/7/27 0027
 **/
public class CommandModelManager {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(CommandModelManager.class);
    private final static ConcurrentHashMap<Integer, CommandModel> requestMapping = new ConcurrentHashMap<>();

    public static CommandModel getCommandModel(Integer cmd){
        if (requestMapping.isEmpty()){
            logger.error("CMD -> Message  is null !");
            return null;
        }
        return requestMapping.get(cmd);
    }

    public static void initializeCommandCode(Map<Integer, CommandCode> requestMapping)throws Exception{
        doCommandCode(BasisCommandCode.getMap());
        if (null != requestMapping){
            doCommandCode(requestMapping);
        }
    }


    private static void doCommandCode(Map<Integer, CommandCode> requestMappingMap)throws Exception{
        Collection<CommandCode> collection = requestMappingMap.values();
        for (CommandCode v : collection){
            requestMapping.put(v.cmd(), CommandModel.builder()
                    .request((ZebraBaseMessage) v.request().getConstructor().newInstance())
                    .cmd(v.cmd())
                    .commandType(v.commandType())
                    .poolType(v.poolType())
                    .processorType(v.processorType())
                    .verifyType(v.verifyType())
                    .build());
        }
    }

    public static String buildCmds(){
        return StrUtil.join(",", requestMapping.keySet()) + ",";
    }

    public static Collection<CommandModel> buildCommandModels(){
        return requestMapping.values();
    }



}
